﻿using System;
using System.Linq;
using SL.MVVMS.RIA;
using RIATestCollection.Web;
using System.ServiceModel.DomainServices.Client;
using System.ComponentModel;
using System.Windows.Data;
using System.Collections.Generic;

namespace RIATestCollection
{
    public class ContactsViewModel : SL.MVVMS.RIA.ViewModel
    {
        ContactContext domainContext;

        public ContactsViewModel()
        {
            domainContext = new ContactContext();
        }

        public void OnViewLoaded()
        {
            var query = domainContext.GetContactsQuery();
            var op = domainContext.Load<Contact>(query);
            RegisterOperation(op, "Loading Contacts...");
        }


        RIACollectionView<Contact> customerView;
        /// <summary>
        /// Bind this to the your View
        /// </summary>
        public RIACollectionView<Contact> CustomerView
        {
            get
            {
                if (customerView == null)
                {
                    customerView = new RIACollectionView<Contact>(domainContext);
                    using (customerView.DeferRefresh())
                    {
                        customerView.SortDescriptions.Add(new SortDescription("contactName", ListSortDirection.Ascending));
                        customerView.GroupDescriptions.Add(new PropertyGroupDescription("contactZip"));
                    }

                }
                return customerView;
            }
        }

        public void OnViewExit()
        {
            if (domainContext.HasChanges)
                domainContext.SubmitChanges();
        }
    }
}